package com.coffee.admin.service.common.impl;

import com.alibaba.fastjson.JSONObject;
import com.coffee.admin.api.common.query.SmsCodeQuery;
import com.coffee.admin.api.common.query.SmsTemplateQuery;
import com.coffee.admin.api.common.result.SmsCodeResult;
import com.coffee.admin.api.common.service.SmsCodeService;
import com.coffee.admin.api.merchant.query.MerchantQuery;
import com.coffee.admin.api.platform.query.PlatformQuery;
import com.coffee.admin.api.supplier.query.SupplierQuery;
import com.coffee.admin.service.common.bean.SmsCode;
import com.coffee.admin.service.common.bean.SmsTemplate;
import com.coffee.admin.service.common.dao.SmsCodeDao;
import com.coffee.admin.service.common.dao.SmsTemplateDao;
import com.coffee.admin.service.merchant.bean.Merchant;
import com.coffee.admin.service.merchant.dao.MerchantDao;
import com.coffee.admin.service.platform.bean.Platform;
import com.coffee.admin.service.platform.dao.PlatformDao;
import com.coffee.admin.service.supplier.bean.Supplier;
import com.coffee.admin.service.supplier.dao.SupplierDao;
import com.coffee.core.entity.Page;
import com.coffee.core.entity.PagerInfo;
import com.coffee.core.enums.ExceptionEnum;
import com.coffee.core.enums.SmsSourceEnum;
import com.coffee.core.exception.BusinessException;
import com.coffee.core.exception.ValidateBusinessException;
import com.coffee.core.util.*;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import java.util.*;


@DubboService(dynamic = true)
public class SmsCodeServiceImpl implements SmsCodeService {
    private static final Logger logger = LoggerFactory.getLogger(SmsCodeServiceImpl.class);

    @Resource
    private SmsCodeDao smsCodeDao;
    @Resource
    private SmsTemplateDao smsTemplateDao;
    @Resource
    private PlatformDao platformDao;
    @Resource
    private SupplierDao supplierDao;
    @Resource
    private MerchantDao merchantDao;
    @Value("${parameter.yunpian.url}")
    private String url;
    @Value("${parameter.yunpian.apikey}")
    private String apikey;

    @Override
    public Page<SmsCodeResult> getPager(SmsCodeQuery param, PagerInfo pr) {
        Page<SmsCodeResult> pager = new Page<SmsCodeResult>(pr.getStart(), pr.getPageSize());
        Integer count = smsCodeDao.count(param);
        pager.setTotalPage(count);
        if (count > 0) {
            List<SmsCode> list = smsCodeDao.page(param, pr.getStart(), pr.getPageSize());
            pager.setData(DTOUtils.convertList(list, SmsCodeResult.class));
        }
        return pager;
    }

    @Override
    public Integer count(SmsCodeQuery param) {
        Integer count = smsCodeDao.count(param);
        return count;
    }

    @Override
    public SmsCodeResult getDetail(Integer id) {
        SmsCode item = smsCodeDao.findById(id);
        if (item == null) {
            return null;
        }
        SmsCodeResult result = new SmsCodeResult();
        BeanUtilExt.copyProperties(result, item);

        return result;
    }

    @Override
    public List<SmsCodeResult> getList(SmsCodeQuery param, PagerInfo pr) {
        List<SmsCode> list = smsCodeDao.page(param, pr.getStart(), pr.getPageSize());
        return DTOUtils.convertList(list, SmsCodeResult.class);
    }

    @Override
    public List<SmsCodeResult> getList(SmsCodeQuery param) {
        List<SmsCode> list = smsCodeDao.page(param, 0, Integer.MAX_VALUE);
        return DTOUtils.convertList(list, SmsCodeResult.class);
    }

    @Override
    public List<SmsCodeResult> getList() {
        SmsCodeQuery param = new SmsCodeQuery();
        List<SmsCode> list = smsCodeDao.page(param, 0, Integer.MAX_VALUE);
        return DTOUtils.convertList(list, SmsCodeResult.class);
    }


    @Override
    public void delete(Integer id) {
        smsCodeDao.deleteById(id);
    }

    @Override
    public void addOrUpdate(SmsCodeResult result) throws BusinessException {
        SmsCode item = new SmsCode();
        BeanUtilExt.copyProperties(item, result);
        if (item.getId() == null) {
            item.setCreateTime(new Date());
            smsCodeDao.insert(item);
        } else {
            SmsCode tmp = smsCodeDao.findById(item.getId());
            if (tmp == null) {
                throw new BusinessException(ExceptionEnum.ERROR_0002.getCode(), ExceptionEnum.ERROR_0002.getMessage());
            }
            smsCodeDao.updateById(item);
        }
    }

    @Override
    public Map<Integer, SmsCodeResult> getItemMap(Set<Integer> idSet) {
        Map<Integer, SmsCodeResult> map = new HashMap<Integer, SmsCodeResult>();
        List<SmsCode> list = smsCodeDao.findByIds(StringUtil.setToList(idSet));
        List<SmsCodeResult> resultList = DTOUtils.convertList(list, SmsCodeResult.class);
        for (SmsCodeResult item : resultList) {
            map.put(item.getId(), item);
        }
        return map;
    }

    @Override
    public Map<Integer, SmsCodeResult> getItemMap() {
        Map<Integer, SmsCodeResult> map = new HashMap<Integer, SmsCodeResult>();
        SmsCodeQuery param = new SmsCodeQuery();
        List<SmsCode> list = smsCodeDao.page(param, 0, Integer.MAX_VALUE);
        List<SmsCodeResult> resultList = DTOUtils.convertList(list, SmsCodeResult.class);
        for (SmsCodeResult item : resultList) {
            map.put(item.getId(), item);
        }
        return map;
    }

    @Override
    public boolean validateSmsCode(String mobile, String verificationCode, SmsSourceEnum smsSource) {
        Date smsCodeCreateTime = DateUtil.addMinutes(new Date(), -DEFAULT_SMS_AVAILABLE_MINUTES);
        // 查询10分钟之内有没有这个短信

        SmsCode smsCode = smsCodeDao.findLastSmsCode(mobile, verificationCode, smsSource.getCode(), smsCodeCreateTime);

        return smsCode != null;
    }

    @Override
    public String getSmsTemplate(String smsType) throws BusinessException {
        SmsTemplateQuery query = new SmsTemplateQuery();
        query.setCode(smsType);
        SmsTemplate smsTemplate = smsTemplateDao.findFirst(query);
        ValidateBusinessException.assertNonNull(smsTemplate, ExceptionEnum.ERROR_1227);
        return smsTemplate.getContent();
    }

    @Override
    public String sendVerificationCodeSms(String smsType, String mobile, String verificationCode) throws BusinessException {
        //手机号码校验
        CheckMobileUtil.checkMobile(mobile);
        ValidateBusinessException.assertStringNotBlank(smsType, ExceptionEnum.ERROR_1209);

        SmsTemplateQuery query = new SmsTemplateQuery();
        query.setCode(smsType);
        SmsTemplate smsTemplate = smsTemplateDao.findFirst(query);
        ValidateBusinessException.assertNonNull(smsTemplate, ExceptionEnum.ERROR_1227);

        if (SmsSourceEnum.USER_LOGIN.getCode().equals(smsType)) {
            MerchantQuery merchantQuery = new MerchantQuery();
            merchantQuery.setMobile(mobile);
            Merchant user = merchantDao.findFirst(merchantQuery);
            ValidateBusinessException.assertNonNull(user, ExceptionEnum.ERROR_1412);
        }

        SmsSourceEnum smsSourceEnums = SmsSourceEnum.getByCode(smsTemplate.getCode());
        ValidateBusinessException.assertNonNull(smsSourceEnums, ExceptionEnum.ERROR_1211);

        // 记录短信发送
        SmsCode smsCode = new SmsCode();
        smsCode.setMobile(mobile);
        smsCode.setVerificationCode(verificationCode);
        smsCode.setSource(smsSourceEnums.getCode());
        smsCode.setIsValid("Y");
        smsCode.setCreateTime(new Date());
        smsCodeDao.insert(smsCode);
        return null;
    }

}
